//****************************************************************
//* Copyright (c) 2008 Ford Motor Company. All Rights Reserved.
//*
//* $$Workfile:   FullEconomicsDao.java  $$
//* $$Revision:   1.7  $$
//* $$Author:   aponte  $$
//* $$Date:   Dec 18 2008 12:47:06  $$
//*
//*****************************************************************
package ar.com.ford.it.fullEconomics.persistence.dao;

import java.io.FileNotFoundException;
import java.sql.Timestamp;
import java.util.Collection;
import oracle.toplink.expressions.Expression;
import oracle.toplink.expressions.ExpressionBuilder;
import oracle.toplink.queryframework.ReadAllQuery;
import oracle.toplink.sessions.Session;
import oracle.toplink.tools.sessionmanagement.SessionManager;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc02Coststvers;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesf01Fulleconom;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesf02Fullecoitm;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp02Commodity;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp04Supply;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;
import com.ford.it.persistence.PersistenceManager;
import com.ford.it.persistence.Query;
import com.ford.it.persistence.Transaction;

public class FullEconomicsDao extends Dao {

	private static final String CLASS_NAME = FullEconomicsDao.class.getName();

	private static final ILogger log = LogFactory.getInstance().getLogger(
			CLASS_NAME);

	/**
	 * Busca, si lo hay, el Full Economics asociado a la Cost Structure Version
	 * pasada por parametro
	 * 
	 * @param costStrVersion
	 * @return
	 * @throws PersistenceException
	 */
	public Teesf01Fulleconom findFullEconomicsByCostStrVersion(
			Teesc02Coststvers costStrVersion) throws PersistenceException {

		String METHOD_NAME = "findFullEconomicsByCostStrVersion";
		log.entering(CLASS_NAME, METHOD_NAME);

		Teesf01Fulleconom ret = null;
		PersistenceManager pm = null;

		pm = PersistenceUtil.getPersistenceManager();
		Query query = pm.newQuery("findFullEconomicsByCostStrVersion",
				Teesf01Fulleconom.class);
		query.setParameters(costStrVersion);

		ret = (Teesf01Fulleconom) pm.executeQuery(query);

		log.exiting(CLASS_NAME, METHOD_NAME);
		return ret;
	}

	/**
	 * Busca los Full Economics asociado con los parametros seleccionados
	 * 
	 * @param
	 * @return
	 * @throws PersistenceException
	 */
	public Collection<Teesf01Fulleconom> findFullEconomicsByStruct(
			Teess01Supplier supplier, Teesp04Supply supply, Teesp01Part part,
			Timestamp dateMin, Timestamp dateMax, Teesg01Plant teesg01Plant,
			String dateTypeSel, String userActionTypeSel, String userId,
			Teesp02Commodity teesp02Commodity, Timestamp dateMinEL1,
			Timestamp dateMaxEL1, Timestamp dateMinEL2, Timestamp dateMaxEL2,
			String estado) throws PersistenceException {

		String METHOD_NAME = "findFullEconomicsByStruct";
		log.entering(CLASS_NAME, METHOD_NAME);

		// Verificar:
		// 1-OK - Supplier -> costrtvr - costsrt - supply - supplier
		// 2-OK - Part -> costrtvr - costsrt - supply - part
		// 3-Date - Type - Ver EffDateIn
		// 4-OK - User
		// 5-Vehicle
		// 6-OK - Econ level date 1
		// 7-OK - Econ level date 2
		// 8-Estado
		// 9-mostrar ultimos aprovados
		// 10-OK - Commodity

		Collection<Teesf01Fulleconom> ret = null;
		PersistenceManager pm = null;

		Session session = null;

		try {
			session = SessionManager.getManager().getSession(
					this.getSessionName());
		} catch (FileNotFoundException e) {
			throw new PersistenceException(e);
		}
		ExpressionBuilder builder = new ExpressionBuilder();
		ReadAllQuery query = new ReadAllQuery(Teesf01Fulleconom.class);

		Expression exp = null;

		// comparo la planta
		exp = builder.get("eesf01PlantCodeC").equal(teesg01Plant);

		String dateField = "";

		// Si selecciono las fechas
		if (dateMin != null && dateMax != null) {
			// comparo la fecha dependiendo de cual sea
			if (dateTypeSel.equals("Creation")) {
				dateField = "eesf01CreateS";
			}
			if (dateTypeSel.equals("Proposal")) {
				dateField = "eesf01FulleProposalS";
			}
			if (dateTypeSel.equals("Approval")) {
				dateField = "eesf01FulleApprovalS";
			}
			// TODO: ver contra que se compara
			if (dateTypeSel.equals("EffDateIn")) {
				dateField = "eesf01CreateS";
			}
			exp = exp.and(builder.get(dateField).greaterThanEqual(dateMin));
			exp = exp.and(builder.get(dateField).lessThanEqual(dateMax));
		}

		// Verifico el supply - supplier - part si fueron seleccionados
		if (supply != null) {

			if (supply.getTeess01Supplier() != null) {

				if (!supply.getTeess01Supplier().getEess01SupplierClassCodeC()
						.equals("-1")) {
					exp = exp.and(builder.get("teesc02Coststvers").get(
							"teesc01Coststruct").get("teesp04Supply").get(
							"teess01Supplier").get("eess01SupplierClassCodeC")
							.equal(
									supply.getTeess01Supplier()
											.getEess01SupplierClassCodeC()));
				}

				exp = exp.and(builder.get("teesc02Coststvers").get(
						"teesc01Coststruct").get("teesp04Supply").get(
						"teess01Supplier").get("eess01SupplierCodeC").like(
						supply.getTeess01Supplier().getEess01SupplierCodeC()
								+ "%"));

			}
			if (supply.getTeesp01Part() != null) {
				exp = exp.and(builder.get("teesc02Coststvers").get(
						"teesc01Coststruct").get("teesp04Supply").get(
						"teesp01Part").equal(supply.getTeesp01Part()));
			}
		}

		if (userId != null && !userId.equals("")) {
			// Verifico el usuario
			if (userActionTypeSel.equals("Creation")) {
				exp = exp.and(builder.get("eesf01CreateUserC").equal(userId));
			}
			if (userActionTypeSel.equals("Proposal")) {
				exp = exp.and(builder.get("eesf01FulleProposalUserC").equal(
						userId));
			}
			if (userActionTypeSel.equals("Approval")) {
				exp = exp.and(builder.get("eesf01FulleApprovalUserC").equal(
						userId));
			}
		}

		// Si se selecciono el commodity
		if (teesp02Commodity != null) {
			exp = exp.and(builder.get("teesc02Coststvers").get(
					"teesc01Coststruct").get("teesp02Commodity").equal(
					teesp02Commodity));
		}

		// Si selecciono la fecha de N Eco 1 de inicio
		if (dateMinEL1 != null) {
			exp = exp.and(builder.get("eesf01FulleEcolevel1DateY")
					.greaterThanEqual(dateMinEL1));
		}
		// Si selecciono la fecha de N Eco 1 de fin
		if (dateMaxEL1 != null) {
			exp = exp.and(builder.get("eesf01FulleEcolevel1DateY")
					.lessThanEqual(dateMaxEL1));
		}

		// Si selecciono la fecha de N Eco 2 de inicio
		if (dateMinEL2 != null) {
			exp = exp.and(builder.get("eesf01FulleEcolevel2DateY")
					.greaterThanEqual(dateMinEL2));
		}
		// Si selecciono la fecha de N Eco 2 de fin
		if (dateMaxEL2 != null) {
			exp = exp.and(builder.get("eesf01FulleEcolevel2DateY")
					.lessThanEqual(dateMaxEL2));
		}

		query.setSelectionCriteria(exp);

		ret = (Collection<Teesf01Fulleconom>) session.executeQuery(query);

		log.exiting(CLASS_NAME, METHOD_NAME);
		return ret;
	}
    
    /**
     * Elimina de forma definitiva de la base de datos el fullEE pasado por
     * parametro
     * 
     * @param fullEE
     */
    public void createFullEconomicItem(Teesf02Fullecoitm fullEconItem)
            throws PersistenceException {

        String METHOD_NAME = "createFullEconomic";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = PersistenceUtil.getTransaction();
        if (tx != null) {
            tx.registerInsert(fullEconItem);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }
    
    /**
     * Elimina de forma definitiva de la base de datos el fullEE pasado por
     * parametro
     * 
     * @param fullEE
     */
    public void createFullEconomic(Teesf01Fulleconom fullEcon)
            throws PersistenceException {

        String METHOD_NAME = "createFullEconomic";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = PersistenceUtil.getTransaction();
        if (tx != null) {
            tx.registerInsert(fullEcon);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }
	
    /**
     * Elimina de forma definitiva de la base de datos el fullEE pasado por
     * parametro
     * 
     * @param fullEE
     */
    public void deleteFullEconomic(Teesf01Fulleconom teesf01Fulleconom)
            throws PersistenceException {

        String METHOD_NAME = "deleteFullEconomic";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = PersistenceUtil.getTransaction();
        if (tx != null) {
            tx.registerDelete(teesf01Fulleconom);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }
    
    
    /**
     * Elimina de forma definitiva de la base de datos el fullEE item pasado por
     * parametro
     * 
     * @param fullEE
     */
    public void deleteFullEconomicItem(Teesf02Fullecoitm teesf02Fullecoitm)
            throws PersistenceException {

        String METHOD_NAME = "deleteFullEconomicItem";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = PersistenceUtil.getTransaction();
        if (tx != null) {
            tx.registerDelete(teesf02Fullecoitm);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }


}
